package com.studyyoun.android.nonghe.person.activity;
/**
 * Created by zhaolong on 2017/10/5.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.activity.CommonBaseActivity;
import com.studyyoun.android.androidcommonbaselibrary.execut.ExecutorFunction;
import com.studyyoun.android.androidcommonbaselibrary.glide.CommonGlideUtils;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.exce.OkhttpException;
import com.studyyoun.android.androidcommonbaselibrary.utils.BitmapUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.CommonLoadingUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.FastJsonUtil;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.person.model.FileUpLoadingModel;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;
import com.studyyoun.android.nonghe.welcom.activity.LoginActivity;
import com.studyyoun.android.nonghe.welcom.model.UserModel;

import java.io.File;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * class infation
 */
public class PersonActivity extends CommonBaseActivity {
    private View mBackLinearLayout;
    private TextView mHeaderTitleTextView;
    private TextView mMyCountTextView;
    private LinearLayout mNixeLinearLayout;
    private TextView mNixeTextView;
    private TextView mMySignTextView;
    private PopupWindow mMPopupWindow;
    private LinearLayout mMySingnLinearLayout;
    private LinearLayout mAlertPasswordLinearLayout;
    private TextView mAlertPasswordTextView;
    private LinearLayout mAlertUserTitleLayout;

    public final int TAKE_PHOTO = 100;
    public final int CROP_PHOTO = 101;
    public final int CHOOSE_PHOTO = 103;

    private Uri mImageUri;
    private CircleImageView mAlertUserTitleImageView;
    private SoftReference<Bitmap> mSoftReference;
    private String mMImagePath;

    @Override
    protected void getAllIntentExtraDatas(Intent intent) {

    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.activity_person_layout;
    }

    @Override
    protected void commonInitView(View view) {
        mBackLinearLayout = findViewById(R.id.ll_base_back);
        mHeaderTitleTextView = findViewById(R.id.tv_base_header_title);

        mAlertUserTitleLayout = findViewById(R.id.ll_person_alert_title);
        mAlertUserTitleImageView = findViewById(R.id.iv_person_alert_title);

        //昵称
        mNixeLinearLayout = findViewById(R.id.ll_my_nixe);
        mNixeTextView = findViewById(R.id.tv_my_nixe);

        //签名
        mMySingnLinearLayout = findViewById(R.id.ll_my_sign);
        mMySignTextView = findViewById(R.id.tv_my_sign);

        mAlertPasswordLinearLayout = findViewById(R.id.ll_person_alert_password);
        mAlertPasswordTextView = findViewById(R.id.tv_person_alert_password);

        mMyCountTextView = findViewById(R.id.tv_my_count);
    }

    @Override
    protected void commonFunction() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        UserModel userModel = CommonUserHelper.getUserModel();

        String imgUrl = userModel.getImgUrl();
        if (!TextUtils.isEmpty(imgUrl)) {
            imgUrl = HttpUrlHelper.BaseImageHost + imgUrl;
            LogUtils.d("加载头像 " + imgUrl);
            CommonGlideUtils.showImageView(mAlertUserTitleImageView.getContext(), R.mipmap.default_title, imgUrl, mAlertUserTitleImageView);
        }
        /**
         * 我的帐号
         * 手机号 不可修改
         */
        mMyCountTextView.setText(userModel.getUserName());

        /**
         * 昵称可修改
         * 默认为显示账号
         */
        mNixeTextView.setText(userModel.getNixe());
        /***
         * 签名
         */
        String userFlag = userModel.getUserFlag();
        if (TextUtils.isEmpty(userFlag)) {
            mMySignTextView.setText("暂无签名，点击设置");
        } else {
            mMySignTextView.setText(userFlag);
        }
    }

    @Override
    protected void commonDelayFunction() {
        mHeaderTitleTextView.setText("个人中心");
        mBackLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mNixeLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertNixeFunction(1);
            }
        });
        mMySingnLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertNixeFunction(2);
            }
        });
        mAlertPasswordLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertNixeFunction(3);
            }
        });
        mAlertUserTitleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertTitleImageFunction();
            }
        });
    }

    private void showAlertTitleImageFunction() {
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        final View popupWindow_view = View.inflate(mContext, R.layout.item_person_alert_header, null);

        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        mMPopupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);


        //焦点设置
        mMPopupWindow.setFocusable(true);
        //设置点击背景不消失
        mMPopupWindow.setOutsideTouchable(true);
        mMPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置透明背景
        mMPopupWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));
        //设置动画

        mMPopupWindow.setAnimationStyle(com.studyyoun.android.androidcommonbaselibrary.R.style.popwin_from_bottom_anim_style);
        //显示
        mMPopupWindow.showAtLocation(mNixeLinearLayout, Gravity.NO_GRAVITY, 0, 0);
        popupWindow_view.findViewById(R.id.bt_cancle_alert_nixe).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mMPopupWindow != null) {
                    mMPopupWindow.dismiss();
                    mMPopupWindow = null;
                }
            }
        });

        popupWindow_view.findViewById(R.id.bt_alert_header_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                openCapTureFunction();
                //相机
                if (mMPopupWindow != null) {
                    mMPopupWindow.dismiss();
                    mMPopupWindow = null;
                }
            }
        });

        popupWindow_view.findViewById(R.id.bt_alert_header_select2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                openCapTureGroupFunction();
                //相册
                if (mMPopupWindow != null) {
                    mMPopupWindow.dismiss();
                    mMPopupWindow = null;
                }
            }
        });


    }

    private void openCapTureGroupFunction() {
        //同样new一个file用于存放照片
        File imageFile = new File(Environment
                .getExternalStorageDirectory(), "outputImage.jpg");
        if (imageFile.exists()) {
            imageFile.delete();
        }
        try {
            imageFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        //转换成Uri
        mImageUri = Uri.fromFile(imageFile);
        mMImagePath = imageFile.getPath();
        //开启选择呢绒界面
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        //设置可以缩放
        intent.putExtra("scale", true);
        //设置可以裁剪
        intent.putExtra("crop", true);
        intent.setType("image/*");
        //设置输出位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        //开始选择
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    private void openCapTureFunction() {
        try {
            // new一个File用来存放拍摄到的照片
            // 通过getExternalStorageDirectory方法获得手机系统的外部存储地址
            File imageFile = new File(Environment
                    .getExternalStorageDirectory(), "wisdom_tempImage.jpg");
            // 如果存在就删了重新创建
            try {
                if (imageFile.exists()) {
                    imageFile.delete();
                }
                imageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 将存储地址转化成uri对象
            mImageUri = Uri.fromFile(imageFile);
            // 设置打开照相的Intent
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            // 设置相片的输出uri为刚才转化的imageUri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
            // 开启相机程序，设置requestCode为TOKE_PHOTO
            startActivityForResult(intent, TAKE_PHOTO);
        } catch (Exception e) {

        }
    }

    /**
     * 1 显示修改昵称
     * 2 显示修改签名
     */
    private void showAlertNixeFunction(final int type) {
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        final View popupWindow_view = View.inflate(mContext, R.layout.item_person_alert_nixe, null);

        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        mMPopupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);


        //焦点设置
        mMPopupWindow.setFocusable(true);
        //设置点击背景不消失
        mMPopupWindow.setOutsideTouchable(true);
        mMPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置透明背景
        mMPopupWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));
        //设置动画

        mMPopupWindow.setAnimationStyle(com.studyyoun.android.androidcommonbaselibrary.R.style.popwin_from_bottom_anim_style);
        //显示
        mMPopupWindow.showAtLocation(mNixeLinearLayout, Gravity.NO_GRAVITY, 0, 0);

        //标题
        TextView titleTextView = popupWindow_view.findViewById(R.id.tv_person_alert_information_header);
        final TextView showTextCountTextView = popupWindow_view.findViewById(R.id.tv_alert_nixe_show_text_count);
        final EditText nixeInputEditText = popupWindow_view.findViewById(R.id.et_alert_nixe_text_input);

        final EditText alertPasswordEditText1 = popupWindow_view.findViewById(R.id.et_alert_password_text_input);
        final EditText alertPasswordEditText2 = popupWindow_view.findViewById(R.id.et_alert_password_text_input2);
        //修改密码
        LinearLayout alertPasswordLinearLayout = popupWindow_view.findViewById(R.id.ll_alert_password);
        //其他
        FrameLayout alertCommonFrameLayout = popupWindow_view.findViewById(R.id.fl_alert_common_information);
        switch (type) {
            case 1:
                alertCommonFrameLayout.setVisibility(View.VISIBLE);
                alertPasswordLinearLayout.setVisibility(View.GONE);
                titleTextView.setText("修改昵称");
                nixeInputEditText.setHint("修改昵称(限10字以内)");
                nixeInputEditText.setText(CommonUserHelper.getUserModel().getNixe());
                String inputText = nixeInputEditText.getText().toString();
                nixeInputEditText.setMinLines(2);
                nixeInputEditText.setMaxLines(2);
                nixeInputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
                if (!TextUtils.isEmpty(inputText)) {
                    showTextCountTextView.setText("还可以输入" + (10 - nixeInputEditText.length()) + "字");
                } else {
                    showTextCountTextView.setText("还可以输入10字");
                }
                break;
            case 2:
                alertCommonFrameLayout.setVisibility(View.VISIBLE);
                alertPasswordLinearLayout.setVisibility(View.GONE);
                titleTextView.setText("修改签名");
                nixeInputEditText.setHint("修改签名(限30字以内)");
                nixeInputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)});
                nixeInputEditText.setText(CommonUserHelper.getUserModel().getUserFlag());
                String inputText2 = nixeInputEditText.getText().toString();
                nixeInputEditText.setMinLines(4);
                nixeInputEditText.setMaxLines(4);
                if (!TextUtils.isEmpty(inputText2)) {
                    showTextCountTextView.setText("还可以输入" + (30 - nixeInputEditText.length()) + "字");
                } else {
                    showTextCountTextView.setText("还可以输入30字");
                }
                break;

            case 3:
                titleTextView.setText("修改密码");
                alertCommonFrameLayout.setVisibility(View.GONE);
                alertPasswordLinearLayout.setVisibility(View.VISIBLE);
                break;
        }


        nixeInputEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String string = charSequence.toString();
                switch (type) {
                    case 1:
                        if (!TextUtils.isEmpty(string)) {
                            showTextCountTextView.setText("还可以输入" + (10 - string.length()) + "字");
                        } else {
                            showTextCountTextView.setText("还可以输入10字");
                        }
                        break;
                    case 2:
                        if (!TextUtils.isEmpty(string)) {
                            showTextCountTextView.setText("还可以输入" + (30 - string.length()) + "字");
                        } else {
                            showTextCountTextView.setText("还可以输入30字");
                        }
                        break;
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        popupWindow_view.findViewById(R.id.bt_cancle_alert_nixe).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mMPopupWindow != null) {
                    mMPopupWindow.dismiss();
                    mMPopupWindow = null;
                }
            }
        });
        popupWindow_view.findViewById(R.id.bt_commit_alert_nixe).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inputNixeText = nixeInputEditText.getText().toString();
                switch (type) {
                    case 1:
                        commitAlertNixeFunction(inputNixeText);
                        if (mMPopupWindow != null) {
                            mMPopupWindow.dismiss();
                            mMPopupWindow = null;
                        }
                        break;

                    case 2:
                        commitAlertFlagFunction(inputNixeText);
                        if (mMPopupWindow != null) {
                            mMPopupWindow.dismiss();
                            mMPopupWindow = null;
                        }
                        break;
                    case 3:
                        String password1 = alertPasswordEditText1.getText().toString();
                        String password2 = alertPasswordEditText2.getText().toString();
                        if (TextUtils.isEmpty(password1)) {
                            ToastUtils.show("请输入密码", mContext);
                        } else if (TextUtils.isEmpty(password2)) {
                            ToastUtils.show("请再次输入密码", mContext);
                        } else if (!TextUtils.equals(password1, password2)) {
                            ToastUtils.show("两次输入密码不一样 请核对", mContext);
                        } else {
                            commitAlertPasswordFunction(password1);
                            if (mMPopupWindow != null) {
                                mMPopupWindow.dismiss();
                                mMPopupWindow = null;
                            }
                        }

                        break;
                }


            }
        });
    }

    private long mPreTime = 0;

    private void commitAlertPasswordFunction(final String password1) {

        CommonLoadingUtils.getInstance().showLoading(mNixeTextView);
        mPreTime = System.currentTimeMillis();
        //修改密码
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                final String url = HttpUrlHelper.sAlertUserPasswordUrl;
                ConcurrentHashMap<String, String> key = new ConcurrentHashMap<String, String>();
                key.put("id", CommonUserHelper.getUserModel().getUserId() + "");
                key.put("password", password1);
                OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                    @Override
                    public void onSuccess(Object obj) {
                        long flagTime = System.currentTimeMillis() - mPreTime;
                        if (flagTime < 1500) {
                            flagTime = 1500 - flagTime;
                        } else {
                            flagTime = 0;
                        }
                        LogUtils.d("修改密码成功");
                        ToastUtils.show("修改密码成功，请重新登录", mContext);
                        CommonUserHelper.exitUser();

                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                CommonLoadingUtils.getInstance().closeFunction();
                                PersonActivity.this.startActivity(new Intent(PersonActivity.this, LoginActivity.class));
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        PersonActivity.this.finish();
                                    }
                                }, 100);
                            }
                        }, flagTime);


                    }

                    @Override
                    public void onFaile(Object obj) {
                        OkhttpException okhttpException = (OkhttpException) obj;
                        LogUtils.d("修改密码失败 " + ((OkhttpException) obj).exception);
                        ToastUtils.show("修改密码失败" + okhttpException.exception, mContext);
                    }
                });

            }
        }, 300);
    }

    private void commitAlertNixeFunction(final String inputNixeText) {
        //修改昵称
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                final String url = HttpUrlHelper.sAlertUserNixeUrl;
                ConcurrentHashMap<String, String> key = new ConcurrentHashMap<String, String>();
                key.put("id", CommonUserHelper.getUserModel().getUserId() + "");
                key.put("nixe", inputNixeText);
                OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                    @Override
                    public void onSuccess(Object obj) {
                        LogUtils.d("修改昵称成功");
                        UserModel userModel = CommonUserHelper.getUserModel();
                        userModel.setNixe(inputNixeText);
                        CommonUserHelper.saveUserData(userModel);
                        mNixeTextView.setText(inputNixeText);

                    }

                    @Override
                    public void onFaile(Object obj) {
                        OkhttpException okhttpException = (OkhttpException) obj;
                        LogUtils.d("修改昵称失败");
                        ToastUtils.show("修改昵称失败" + okhttpException.exception, mContext);
                    }
                });

            }
        }, 100);
    }

    private void commitAlertFlagFunction(final String inputNixeText) {
        //修改签名
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                final String url = HttpUrlHelper.sAlertUserFlagUrl;
                ConcurrentHashMap<String, String> key = new ConcurrentHashMap<String, String>();
                key.put("id", CommonUserHelper.getUserModel().getUserId() + "");
                key.put("flag", inputNixeText);
                OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                    @Override
                    public void onSuccess(Object obj) {
                        LogUtils.d("修改签名成功");
                        UserModel userModel = CommonUserHelper.getUserModel();
                        userModel.setUserFlag(inputNixeText);
                        CommonUserHelper.saveUserData(userModel);
                        mMySignTextView.setText(inputNixeText);

                    }

                    @Override
                    public void onFaile(Object obj) {
                        OkhttpException okhttpException = (OkhttpException) obj;
                        LogUtils.d("修改签名失败");
                        ToastUtils.show("修改签名失败" + okhttpException.exception, mContext);
                    }
                });

            }
        }, 100);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    handleImageOnKitkat(data);
                }
                break;
            // 从拍照界面返回
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 设置intent为启动裁剪程序
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    // 设置Data为刚才的imageUri和Type为图片类型
                    intent.setDataAndType(mImageUri, "image/*");
                    // 设置可缩放
                    intent.putExtra("scale", true);
                    // 设置输出地址为imageUri
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                    // 开启裁剪,设置requestCode为CROP_PHOTO
                    startActivityForResult(intent, CROP_PHOTO);
                }

                break;
            // 从裁剪界面返回
            case CROP_PHOTO:
                if (resultCode == RESULT_OK) {
                    //通过BitmapFactory将imageUri转化成bitmap
                    CommonLoadingUtils.getInstance().showLoading(mAlertUserTitleImageView);

                    ExecutorFunction.getInstance().addRunnableTask(new Runnable() {
                        @Override
                        public void run() {

                            LogUtils.d("imageUrl is " + mImageUri);
                            LogUtils.d("imageUrl is " + mImageUri.getEncodedPath());

                            displayImage(mImageUri.getEncodedPath());


                        }
                    });

                }

                break;
            default:
                break;
        }

    }

    private void alertUserNetTitle(String content) {
        String url = HttpUrlHelper.sAlertUserHeaderImgUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("imgUrl", content);
        key.put("userId", String.valueOf(CommonUserHelper.getUserModel().getUserId()));
        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("修改成功");
            }

            @Override
            public void onFaile(Object obj) {
                LogUtils.e("修改失败");
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri
                    .getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri
                    .getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果不是document类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        }
        displayImage(imagePath); // 根据图片路径显示图片
        System.err.println(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null,
                null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(final String imagePath) {


        //通过BitmapFactory将imageUri转化成bitmap
        CommonLoadingUtils.getInstance().showLoading(mAlertUserTitleImageView);

        ExecutorFunction.getInstance().addRunnableTask(new Runnable() {
            @Override
            public void run() {

                LogUtils.d("imageUrl is " + imagePath);

                BitmapFactory.Options options = new BitmapFactory.Options();

                //设置加载标识 为true 代表只加载 图片的宽度与高度 而不加载图片的像素内容
                options.inJustDecodeBounds = true;
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                options.inPurgeable = true;
                options.inInputShareable = true;

                BitmapFactory.decodeFile(imagePath, options);

                int outWidth = options.outWidth;
                int outHeight = options.outHeight;

                double scalX = 1;
                double scalY = 1;

                scalX = outWidth * 1.0f / 100;
                scalX = Math.ceil(scalX);
                scalY = outHeight * 1.0f / 100;
                scalY = Math.ceil(scalY);

                if (scalX < 1) {
                    scalX = 1.0f;
                }
                if (scalY < 1) {
                    scalY = 1f;
                }

                scalX = Math.max(scalX, scalY);

                options.inSampleSize = (int) scalX;

                options.inJustDecodeBounds = false;

                //测量图片 并将图片的宽与高的数据 封装在 options中
                mSoftReference= new SoftReference<Bitmap>(BitmapFactory.decodeFile(imagePath, options));


                //设置显示
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mSoftReference != null && mSoftReference.get() != null) {
                            mAlertUserTitleImageView.setImageBitmap((Bitmap) mSoftReference.get());
                            Intent intent = new Intent();
                            intent.putExtra("imageUrl", mImageUri);
                            intent.setAction("alert_title_img");
                            mContext.sendBroadcast(intent);
                            File imageFile = new File(Environment
                                    .getExternalStorageDirectory(), "wisdom_tempImage_min" + System.currentTimeMillis() + ".jpg");
                            // 如果存在就删了重新创建
                            try {
                                if (imageFile.exists()) {
                                    imageFile.delete();
                                }
                                imageFile.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }


                            boolean save = BitmapUtils.save(mSoftReference.get(), imageFile, Bitmap.CompressFormat.PNG);

                            String url = HttpUrlHelper.sFileUpLoaddUrl;

                            ConcurrentHashMap<String, Object> key = new ConcurrentHashMap<String, Object>();
                            key.put("filType", "user");
                            key.put("file", imageFile);

                            OkhttpCommonClient.sentPostFileRequest(url, key, new OkhttpCommonCallBack() {
                                @Override
                                public void onSuccess(Object obj) {

                                    FileUpLoadingModel model = FastJsonUtil.toBean(obj.toString(), FileUpLoadingModel.class);
                                    if (model.code == 1000) {
                                        LogUtils.d("上传成功" + model.content);
                                        CommonLoadingUtils.getInstance().closeFunction();
                                        UserModel userModel = CommonUserHelper.getUserModel();
                                        userModel.setImgUrl(model.content);
                                        CommonUserHelper.saveUserData(userModel);
                                        alertUserNetTitle(model.content);
                                    } else {
                                        ToastUtils.show("头像上传失败", mContext);
                                    }
                                }

                                @Override
                                public void onFaile(Object obj) {
                                    LogUtils.d("上传失败");
                                    CommonLoadingUtils.getInstance().closeFunction();
                                }
                            });
                        }
                    }
                });

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSoftReference != null) {
            if (mSoftReference.get() != null) {
                if (!mSoftReference.get().isRecycled()) {
                    mSoftReference.get().recycle();
                }
            }
        }
    }
}
